package com.zty.user.delayQueue;

import com.alibaba.fastjson.JSON;
import com.zty.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Date;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author ZTY
 * @Description 将任务发布到队列，写到Redis中
 * @Date 2:03 2023-12-21
 **/

@Service
@Slf4j
public class MassTaskService {

    @Resource
    private RedisUtil redisUtil;

    //  存在Redis中的key
    private static final String MASS_TASK_KEY = "massTaskMail";

    /**
     * 发布延时任务
     *
     * @param massMailTask
     */
    public void pushMassMailTaskQueue(MassMailTask massMailTask) {
        Date startTime = massMailTask.getStartTime();

        //  无需执行定时任务
        if (startTime == null) {
            return;
        }
        if (startTime.compareTo(new Date()) <= 0) {
            return;
        }

        log.info("定时群发任务加入延时队列，massMailTask:{}", JSON.toJSON(massMailTask));
        redisUtil.zAdd(MASS_TASK_KEY, massMailTask.getTastId().toString(), startTime.getTime());
    }

    /**
     * 到点拉取延时任务
     *
     * @return
     */
    public Set<Long> poolMassTaskQueue() {
        Set<String> taskIdSet = redisUtil.rangeByScore(MASS_TASK_KEY, 0, System.currentTimeMillis());
        log.info("获取延迟群发任务，taskIdSet：{}", JSON.toJSON(taskIdSet));
        //  没有返回空集合
        if (CollectionUtils.isEmpty(taskIdSet)) {
            return Collections.emptySet();
        }
        redisUtil.removeZsetList(MASS_TASK_KEY, taskIdSet);
        return taskIdSet.stream().map(n -> Long.parseLong(n)).collect(Collectors.toSet());
    }

}
